// goods/pages/submitOrder/submitOrder.js
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let login = require('../../../common/script/login');
let wxParse = require('../../wxParse/wxParse.js');
const utils = require('../../../utils/util.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: null,
    cart2Data: null,
    cart3Data: null,
    http: api.http,
    showModal: false,
    concent_list: ['微信支付', '会员卡支付'],
    curIndex: 0,
    memberData: null
  },
  // 隐藏模态对话框
  hideModal() {
    const that = this;
    that.setData({
      showModal: false
    });
  },
  // 显示模态对话框
  showModel() {
    const that = this;
    let memberData = wx.getStorageSync('memberData')
    if (memberData) {
      that.setData({
        showModal: true,
        memberData: memberData,
      });
    } else {
      that.debounces()
    }
  },
  // 选择模态框
  choose(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      curIndex: index
    })
  },
  getCart2Data() {
    const that = this;
    let data = {
      goods_num: that.data.goodsNum,
      goods_id: that.data.goodsId,
      token: wx.getStorageSync('token'),
      select_store_id: that.data.storeId,
      address_id: 0
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cart2, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          cart2Data: res.data.result.storeShippingCartList[0].cartList[0],
        })

      }
    })
  },
  getCart3Data() {
    const that = this;
    let data = {
      goods_num: that.data.goodsNum,
      goods_id: that.data.goodsId,
      token: wx.getStorageSync('token'),
      select_store_id: that.data.storeId,
      address_id: 0,
      type: "miniapp",
      act: ""

    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cart3, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          cart3Data: res.data.result,
        })

      }
    })
  },
  //添加收货地址
  addSite() {
    const that = this
    wx.chooseAddress({
      success: (res) => {
        console.log(res, 99999)
        if (res.errMsg = 'chooseAddress:ok') {
          that.setData({
            address: res
          })
        }
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },
  debounces: utils.throttle(function (e) {
    this.setData({
      showModal: false
    });
    this.onConfirm()
  }, 5000),
  onConfirm() {
    const that = this;
    let data = {
      goods_num: that.data.goodsNum,
      goods_id: that.data.goodsId,
      token: wx.getStorageSync('token'),
      select_store_id: that.data.storeId,
      address_id: 0,
      type: "miniapp",
      act: "submit_order",
      wxaddress: JSON.stringify(that.data.address)
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.cart3, data).then(res => {
      console.log(res, 787878)
      wx.hideLoading();
      if (res.data.status == 1) {
        let amountData = {
          token: wx.getStorageSync('token'),
          trade_type: "JSAPI",
          master_order_sn: res.data.result,
          account: that.data.cart3Data.order_amount
        }
        wx.showLoading({
          title: '加载中...',
        })
        // curIndex==0 是微信支付，curIndex==1是会员卡支付
        let curIndex = that.data.curIndex
        if (curIndex == 0) {
          myRequest.EasyHttp.post(api.reqUrls.doPay, amountData).then(prop => {
            wx.hideLoading();
            if (prop.data.status == 1) {
              wx.requestPayment({ // 调取支付
                timeStamp: prop.data.result.timeStamp.toString(),
                nonceStr: prop.data.result.nonceStr,
                package: prop.data.result.package,
                signType: prop.data.result.signType,
                paySign: prop.data.result.sign,
                success(res) {
                  if (res.errMsg == "requestPayment:ok") {
                    console.log(111)

                    wx.redirectTo({
                      url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${prop.data.result.master_order_sn}&type=1`
                    })
                  } else {
                    console.log(222)
                    wx.showModal({
                      content: '付款失败',
                      showCancel: false,
                      confirmText: '我知道了',
                      confirmColor: '#ff5151',
                      success(e) {
                        if (e.confirm) {
                          wx.redirectTo({
                            url: `/goods/pages/order/order`
                          })
                        }
                      }
                    })
                  }
                },
                fail(res) {
                  wx.showModal({
                    content: '付款失败',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {
                        console.log(333)
                        wx.redirectTo({
                          url: `/goods/pages/order/order`
                        })
                      }
                    }
                  })
                }
              })
            }
          })
        } else {
          myRequest.EasyHttp.post(api.reqUrls.cardDoPay, amountData).then(prop => {
            wx.hideLoading();
            if (prop.data.status == 1) {
              wx.redirectTo({
                url: `/goods/pages/submitOrderSuccess/submitOrderSuccess?orderSn=${prop.data.result.master_order_sn}&type=1`
              })
            } else if (prop.data.status == -1002) {
              // wx.showModal({
              //   content: '会员卡余额不足，是否去充值？',
              //   confirmText: '去充值',
              //   success(e) {
              //     if (e.confirm) {
              //       wx.redirectTo({
              //         url: `/package/pages/recharge/recharge`,
              //       })
              //     } else if (e.cancel) {
              //       wx.redirectTo({
              //         url: `/goods/pages/order/order`
              //       })
              //     }
              //   }
              // })
              wx.showModal({
                content: prop.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    console.log(333)
                    wx.redirectTo({
                      url: `/goods/pages/order/order`
                    })
                  }
                }
              })
            } else {
              wx.showModal({
                content: prop.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {
                  if (e.confirm) {
                    console.log(333)
                    wx.redirectTo({
                      url: `/goods/pages/order/order`
                    })
                  }
                }
              })
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    that.setData({
      goodsId: options.goodsId,
      goodsNum: options.goodsNum,
      storeId: options.storeId

    })
    login.checkLogin().then(res => {
      that.getCart2Data()
      that.getCart3Data()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.getCart2Data()
        that.getCart3Data()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})